package cn.fengLone.pay.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.Model;

import sun.util.logging.resources.logging;
import cn.fengLone.pay.constraint.FengPayContraint;

/**
 * 
 * 一些简单的公共静态方法
 * 
 * @compny 深圳风轮科技有限公司
 * 
 * @author Guo PengFei
 * 
 * @date 2017-08-02
 * 
 * @version V1.0
 * 
 */
public class SimpleUtil {
	
	public static Map<String, String> payMap = null;
	public static Map<String, String> wechatPayMap = null;
	public static Map<String, String> aliPayMap = null;
	public static Map<String, String> b2CGateWayMap = null;
	
	static{
		payMap = getProperties(null,"payNotify");//微信支付、支付宝支付、银联支付测试环境和回调URL配置
		wechatPayMap = getProperties("wechat","wechatPay");  //微信支付应用商户信息
		aliPayMap = getProperties("aliPay","aliPay");  //阿里支付应用商户信息
		b2CGateWayMap = getProperties("unionPay","B2CGateWay");//银联支付应用商户信息
	}
	/**
	 * 生产订单号
	 * 
	 * @param siteToken
	 *            站点口令
	 * @return
	 */
	public synchronized static String getTradeNum() {
		// 得到long类型当前时间
		long l = System.currentTimeMillis();
		// new日期对象
		Date date1 = new Date(l);
		// 转换提日期输出格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		return "PM" + dateFormat.format(date1);
	}

	/**
	 * 获取当前网络ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getClientIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")
					|| ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * 获取本机IP
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getMyIp(){
		Enumeration allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "my ip error";
		}
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
					.nextElement();
			System.out.println(netInterface.getName());
			Enumeration addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address) {
					System.out.println("本机的IP = " + ip.getHostAddress());
					return ip.getHostAddress();
				}
			}
			return null;
		}
		return null;
	}

	/**
	 * 根据路径和文件名称获取properties文件中的属性集合
	 * @param path properties文件上级目录
	 * @param fileName  properties文件名称
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static Map<String, String> getProperties(String path, String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		String filePath = getWebInfAbsolutePath() + File.separator + "classes"
				+ File.separator;
		if (path != null && !path.trim().equals(""))
			filePath += path + File.separator;
		filePath += fileName + ".properties";
		Properties prop = new Properties();
		try {
			// 读取属性文件a.properties
			InputStream in = new BufferedInputStream(new FileInputStream(
					filePath));
			prop.load(in); // /加载属性列表
			map = (Map) prop;
			// path =
			// prop.getProperty("resourceFilePath")+File.separator+fileName;
			in.close();
			return map;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	/**
	 * 获取Web-inf目录的绝对路径
	 * 
	 * @return
	 */
	public static String getWebInfAbsolutePath() {
		String path = null;
		String folderPath = SimpleUtil.class.getProtectionDomain()
				.getCodeSource().getLocation().getPath();
		if (folderPath.indexOf("classes/") > 0) {
			path = folderPath.substring(0, folderPath.indexOf("classes/"));
		}
		return path;
	}
	
	// 商户发送交易时间 格式:YYYYMMDDhhmmss
	public static String getCurrentTime() {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	}
	
	// 商户发送交易时间 格式:YYYYMMDDhhmmss
	public static String getCurrentTime(Timestamp timestamp) {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(timestamp);
	}
	/**
	 * 根据库中保存的支付方式，获取中文支付方式
	 * @param payType
	 * @return
	 */
	public static String getChinesePayType(String payType){
		if(payType.equals(FengPayContraint.ALIPAY_PCPAY)){
			payType = SpringUtil.getI18nMsg("aliPay_pcPay_type");
		}else if (payType.equals(FengPayContraint.B2C_GATEWAY)) {
			payType = SpringUtil.getI18nMsg("unionPay_pcPay_type");
		}else if (payType.equals(FengPayContraint.WECHART_SAO)) {
			payType = SpringUtil.getI18nMsg("wechatPay_sao_type");
		}else if (payType.equals(FengPayContraint.WECHART_APP)) {
			payType = SpringUtil.getI18nMsg("wechatPay_app_type");
		}else{
			payType = "未知的支付方式";
		}
		return payType;
	}
	/**
	 * 根据库中保存的结果，获取中文支付结果
	 * 支付结果  1 微支付  2 支付成功  3 支付失败 4 已关闭  5 已撤销(刷卡支付) 8 退款中
	 * @param payResult 中文支付结果描述
	 * @return
	 */
	public static String getChinesePayResult(char payResult){
		String result = null;
		if(payResult == '1'){
			result = "未支付 ";
		}else if (payResult == '2') {
			result = "支付成功";;
		}else if (payResult == '3') {
			result = "支付失败";;
		}else if (payResult == '4') {
			result = "订单已关闭";;
		}else if (payResult == '5') {
			result = "订单已退款";;
		}else if (payResult == '8') {
			result = "退款中";;
		}else{
			result = "-1 未知的订单结果--"+payResult;;
		}
		return result;
	}
	
	
	/**
	 * 从request中获取所有的参数和值
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public  static Map<String, String> getRequestParam(HttpServletRequest request){
		Map<String, String> resultMap = new HashMap<String,String>();
		Enumeration em = request.getParameterNames();
		 while (em.hasMoreElements()) {
		    String name = (String) em.nextElement();
		    String value = request.getParameter(name);
		    resultMap.put(name, value);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 判断订单状态是否已经变化了
	 * @param payResult 订单状态
	 * @return
	 */
	public static boolean orderIsSucces(char payResult) {
		 //1 微支付  2 支付成功  3 支付失败 4 已关闭  5 已撤销(刷卡支付) 6 用户支付中 暂时不用  7 转入退款 暂时不用  8 退款中
		if(payResult== '2' || payResult== '3' || payResult == '4'|| payResult == '5'){
			//本平台中此订单的支付状态已经改变了，不再查询
			return true;
		}else {
			return false;
		}
		
	}

	public static String getPayResultDe(char payResult) {
		String result = null;
		if(payResult == '1'){
			result = "WAIT_BUYER_PAY";
		}else if (payResult == '2') {
			result = "TRADE_SUCCESS";
		}else if (payResult == '3') {
			result = "TRADE_FAIL";
		}else if (payResult == '4') {
			result = "TRADE_FINISHED";
		}else if (payResult == '5') {
			result = "TRADE_CLOSED";
		}else if (payResult == '8') {
			result = "TRADE_REFU";
		}else{
			result = "-1 未知的订单结果--"+payResult;;
		}
		return result;
	}
}
